package main

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"store/backend"
	"store/bootstrap"
	"store/libs/cache"
	"store/libs/gii"
	"store/libs/helper"
	"store/libs/log"
	"store/models"
	"store/rest"
	"store/task"
	"syscall"
	"time"
)

// @title store API
// @version 1.0
// @description store server.

// @contact.email jhq0113@163.com

// @host 127.0.0.1
// @BasePath /
func main() {
	router := bootstrap.Start()

	router.Static("/web", "./web")
	router.Static("/assets", "./web/assets")

	//加载日志
	logger := log.Start()

	router.Use(log.LogByZap(logger))

	router.Use(log.RecoveryWithZap(logger, true))

	//初始化缓存
	cache.Start()

	//加载路由
	rest.Start(router)
	backend.Start(router)

	//加载orm
	models.Start()

	//非release环境
	if bootstrap.Config.Application.GinMode != "release" {
		//加载代码生成器
		gii.Start(router, models.Orm)

		//开放swagger
		router.Static("/swagger", "./docs")
	}

	//运行task
	go task.Start()

	server := &http.Server{
		Addr:           bootstrap.Config.Application.Addr,
		Handler:        router,
		ReadTimeout:    helper.Int64ToSecond(bootstrap.Config.Application.ReadTimeout),
		WriteTimeout:   helper.Int64ToSecond(bootstrap.Config.Application.WriteTimeout),
		MaxHeaderBytes: bootstrap.Config.Application.MaxHeaderBytes,
	}

	go func() {
		err := server.ListenAndServe()
		if err != nil {
			fmt.Println(err)
		}
	}()

	//优雅退出
	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGINT)
	<-ch
	cxt, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	err := server.Shutdown(cxt)
	if err != nil {
		fmt.Println(err)
	}
}
